//
//  AgentViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/9/6.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "AgentViewController.h"
#import "RentVieitor.h"
#import "AgentCell.h"
#import "AgentDetailViewController.h"
#import "AgentsCell.h"
#import "AgentModel.h"
#import "MJRefresh.h"


@interface AgentViewController ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation AgentViewController {
    
    NSString *_identify;
    UITableView *_tableview;
    NSInteger page;//页码
    UITextField *field;
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = BackgroundColor;
    self.data = [NSMutableArray array];
    page = 1;
    [self creatLeftView];
    [self creatView];
    [self loadData];
}

- (void)creatLeftView {
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(-5, 0, 10, 15);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 20, 20);
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"搜索icon"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(AsearchAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;

    
    UIView *naView = [[UIView alloc] initWithFrame:CGRectMake(0, 5, KWidth-70, 30)];
    naView.backgroundColor =  [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:229/255.0];
    naView.layer.masksToBounds = YES;
    naView.layer.cornerRadius = 2;
    self.navigationItem.titleView = naView;
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @" 经纪人  ";
    label.font = [UIFont systemFontOfSize:14];
    CGSize size = [@" 经纪人  " boundingRectWithSize:CGSizeMake(KWidth, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:label.font} context:nil].size;
    label.frame = CGRectMake(0, 5, size.width, 20);
    label.textColor = [Utils colorConvertFromString:@"#333333"];
    [naView addSubview:label];
    
    field = [[UITextField alloc] initWithFrame:CGRectMake(size.width, 2,naView.frame.size.width-size.width-20 , 26)];
    field.font = [UIFont systemFontOfSize:14];
    field.rightViewMode = UITextFieldViewModeAlways;
    //    field.backgroundColor = [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:229/255.0];
    field.placeholder = @"请输入经纪人的姓名和电话";
    field.layer.masksToBounds = YES;
    field.layer.cornerRadius = 2;
    [naView addSubview:field];
    
    UIButton *canceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    canceBtn.frame = CGRectMake(0, 0, 15, 15);
    [canceBtn setBackgroundImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [canceBtn addTarget:self action:@selector(moveAction) forControlEvents:UIControlEventTouchUpInside];
    field.rightView = canceBtn;
    
    
//    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 40)];
//    bgView.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:bgView];
//    
//    NSArray *textArray = @[@"区域",@"排序"];
//    for (int i=0; i<textArray.count; i++) {
//    
//        UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        selectBtn.frame = CGRectMake(KWidth/2*i+10, 10, KWidth/2-20, 20);
//        selectBtn.tag = 100+i;
//        [selectBtn setBackgroundColor:[UIColor whiteColor]];
//        selectBtn.titleLabel.font = [UIFont systemFontOfSize:14];
//        [selectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 50)];
//        [selectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 50, 0, 0)];
//        [selectBtn setTitleColor:[Utils colorConvertFromString:@"#101010"] forState:UIControlStateNormal];
//        [selectBtn setTitle:textArray[i] forState:UIControlStateNormal];
//        [selectBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
//        [selectBtn setImage:[UIImage imageNamed:@"下拉箭头"] forState:UIControlStateNormal];
//        [bgView addSubview:selectBtn];
//    }
//    
//    //分割线
//    CALayer *MlineLayer = [CALayer layer];
//    MlineLayer.backgroundColor = [[Utils colorConvertFromString:@"#d0d0d0"] CGColor];
//    MlineLayer.frame = CGRectMake((KWidth-1)/2 ,0, 1, 40);
//    [bgView.layer addSublayer:MlineLayer];
}

- (void)creatView {
    
    _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0,0, KWidth, KHeight-20) style:UITableViewStylePlain];
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview .showsHorizontalScrollIndicator = NO;
    _tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableview.dataSource = self;
    _tableview.delegate = self;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KWidth*200/750)];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KWidth*200/750)];
    [view addSubview:imgView];
    imgView.image = [UIImage imageNamed:@"agent_heard"];
    _tableview.tableHeaderView = view;
    
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footRefresh)];
    _identify = @"_Cell";
    [_tableview registerClass:[AgentsCell class] forCellReuseIdentifier:_identify];
    [self.view addSubview:_tableview];
}



//下拉刷新
- (void)headerRefresh {
    
    [self loadData];
    
}

- (void)loadData {

    [self.data removeAllObjects];
    if (self.data == nil) {
        self.data = [NSMutableArray array];
    }
    NSString *url = [NSString stringWithFormat:@"%@agent/list",Main_Url];
    NSDictionary *dic = @{
                          @"city":@"103",
                          @"name":field.text
                          };
    
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        [_tableview.mj_header endRefreshing];
        if ([response[@"code"] isEqualToString:@"10000"]) {
            NSArray *dataArray = response[@"data"];
            for (NSDictionary *dic in dataArray) {
                
                NSDictionary *dataDic = [Utils nullDic:dic];
                AgentModel *model = [AgentModel mj_objectWithKeyValues:dataDic];
                [self.data addObject:model];
                
            }
            [_tableview reloadData];
        
        }else {
            [APPDELEGATE  showPro:response[@"message"]];
        }
        
        
        
    } failure:^(NSError *err) {
        
        
        [_tableview.mj_header endRefreshing];

    }];

}


- (void)footRefresh {
    
    if (field.text == nil) {
        field.text = @"";
    }
    page ++;
    NSString *url = [NSString stringWithFormat:@"%@agent/list",Main_Url];
    NSDictionary *dic = @{
                          @"city":@"103",
                          @"page":[NSString stringWithFormat:@"%ld",page],
                          @"name":field.text
                          };
    
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        [_tableview.mj_footer endRefreshing];
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSArray *dataArray = response[@"data"];
            if (dataArray.count <10) {
                page --;
            }
            for (NSDictionary *dic in dataArray) {
                
                NSDictionary *dataDic = [Utils nullDic:dic];
                AgentModel *model = [AgentModel mj_objectWithKeyValues:dataDic];
                [self.data addObject:model];
            }
            
            [_tableview   reloadData];
           
        }else {
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
        page --;
        [_tableview.mj_footer endRefreshing];
    }];
    
    //    __weak typeof(self)WeakSelf = self;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AgentsCell *cell = [tableView dequeueReusableCellWithIdentifier:_identify forIndexPath:indexPath];
    if (self.data.count > indexPath.row) {
        cell.model = self.data[indexPath.row];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 110;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AgentDetailViewController *AgentVc = [[AgentDetailViewController alloc] init];
    AgentModel *model = self.data[indexPath.row];
    NSString *sn = model.sn;
    if (sn != nil & [sn isEqualToString:@""]==NO) {
        AgentVc.sn = model.sn;
        [self.navigationController pushViewController:AgentVc animated:YES];
    }else {
        [APPDELEGATE showPro:@"数据错误"];
    }
    
}

- (void)selectAction:(UIButton *)button {
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [field endEditing:YES];
}


- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)moveAction {
    
}

- (void)AsearchAction {
    
    if (field.text == nil || [field.text isEqualToString:@""]) {
        
        [APPDELEGATE showPro:@"请输入经纪人姓名"];
        return;
    }
    [self loadData];
}

@end
